package com.authine.cloudpivot.ext.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.authine.cloudpivot.engine.api.model.runtime.BizObjectModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectQueryModel;
import com.authine.cloudpivot.engine.component.query.api.FilterExpression;
import com.authine.cloudpivot.engine.component.query.api.Page;
import com.authine.cloudpivot.engine.component.query.api.helper.PageableImpl;
import com.authine.cloudpivot.engine.enums.type.QueryDisplayType;
import com.authine.cloudpivot.ext.domain.ParamVo;
import com.authine.cloudpivot.ext.model.BaseModel;
import com.authine.cloudpivot.ext.service.SynUserService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.exception.ResultEnum;
import com.authine.cloudpivot.web.api.view.ResponseResult;
import com.google.common.collect.Lists;
import com.taobao.api.ApiException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * @author liujing
 * @version 1.0.0
 * @ClassName GetUserController.java
 * @Description
 * @Date: 2021/3/15
 */
@Api(value = "居民通讯录", tags = "01::EXTAPI::居民通讯录")
@RestController
@RequestMapping("/ext/v1/synUser")
@Slf4j
@Validated
@SuppressWarnings("rawtypes")
public class SynUserController extends BaseController {

    @Autowired
    private SynUserService synUserService;

    @Autowired
    private DubboConfigService dubboConfigService;

    @ApiOperation(value = "居民通讯录--仅新增")
    @PostMapping("/getUser")
    public ResponseResult synUser(@RequestBody ParamVo paramVo) {
        // List<String> list = (List) ids.get("ids");
        String id = paramVo.getId();
        String appkey = paramVo.getAppkey();
        String appsecret = paramVo.getAppsecret();
         String type = paramVo.getType();//---未知错误
//        String type = "1";
        try {
            // synUserService.synUser(list,appkey,appsecret,type);
//            synUserService.synUser(id, appkey, appsecret, type);
            synUserService.synUser(id, appkey, appsecret, type);
        } catch (ApiException e) {
            e.printStackTrace();
            log.info("同步用户时错误,{}", e.getMessage());
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return getOkResponseResult("success " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
            ResultEnum.SUCCESS.getErrMsg());
    }

    @ApiOperation(value = "居民通讯录单个部门用户--仅新增")
    @ApiImplicitParams({
        @ApiImplicitParam(name = "deptId", value = "deptId为部门下没有用户的部门Id(云枢h_org_department中的id)", required = true,
            dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "appkey", value = "appkey", required = true, dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "appsecret", value = "appsecret", required = true, dataType = "String",
            paramType = "query")})
    @GetMapping("/getUserByOneDept")
    public ResponseResult getUserByOneDept(String deptId, String appkey, String appsecret) {
        try {
            log.info("进入接口,传入参数为 deptId = " + deptId + ",appkey = " + appkey + ",appsecret = " + appsecret);
            synUserService.getUserByOneDept(deptId, appkey, appsecret);
        } catch (ApiException e) {
            e.printStackTrace();
            log.info("同步用户时错误,{}", e.getMessage());
        } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
            badHanyuPinyinOutputFormatCombination.printStackTrace();
        }
        return getOkResponseResult("success " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
            ResultEnum.SUCCESS.getErrMsg());
    }

    @SuppressWarnings("unchecked")
    @ApiOperation(value = "居民通讯录--一键同步")
    @PostMapping("/one/click/sync")
    public ResponseResult oneClickSync() {
        List<String> columns = Lists.newArrayList();
        columns.add("deptId");
        columns.add("appkey");
        columns.add("appSecret");
        columns.add("id");
        FilterExpression filter =
            new FilterExpression.Item(BaseModel.sequenceStatus, FilterExpression.Op.Eq, "COMPLETED");
        BizObjectQueryModel query = new BizObjectQueryModel();
        query.setSchemaCode("shangxi_town_code");
        query.setQueryCode("shangxi_town_code");
        query.setFilterExpr(filter);
        BizObjectQueryModel.Options options = new BizObjectQueryModel.Options();
        options.setQueryDisplayType(QueryDisplayType.OVERRIDE);
        options.setCustomDisplayColumns(columns);
        query.setOptions(options);
        query.setPageable(new PageableImpl(0, Integer.MAX_VALUE));
        Page<BizObjectModel> resultPage = dubboConfigService.getBizObjectFacade().queryBizObjects(query);
        List<BizObjectModel> content = Lists.newArrayList();
        if (resultPage != null) {
            content = (List<BizObjectModel>)resultPage.getContent();
            for (BizObjectModel bizObjectModel : content) {
                if (bizObjectModel.getData().get("deptId") == null) {
                    continue;
                }
                String deptId = String.valueOf(bizObjectModel.getData().get("deptId"));
                String appkey = String.valueOf(bizObjectModel.getData().get("appkey"));
                String appsecret = String.valueOf(bizObjectModel.getData().get("appSecret"));
                try {
                    synUserService.oneClickSync(deptId, appkey, appsecret);
                    // 每个请求等待30秒
                    Thread.sleep(30000);
                } catch (ApiException e) {
                    e.printStackTrace();
                    log.info("同步用户时错误,{}", e.getMessage());
                } catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
                    badHanyuPinyinOutputFormatCombination.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    log.info("sleep异常,{}", e.getMessage());
                }
            }

        }
        return getOkResponseResult("success " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()),
            ResultEnum.SUCCESS.getErrMsg());
    }

}
